package cn.btks.backstagemanage.user.repository;

import cn.btks.backstagemanage.user.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

/**
 * @Author lijun
 * @Date 2021/1/7 11:21
 */
@Repository
public interface UserRepository extends JpaRepository<User,Long>, JpaSpecificationExecutor<User> {

    /**
     * 根据用户名查询用户
     * @param userName
     * @return
     */
    User findByUsername(String userName);

    /**
     * 根据用户ID查询关联表数量
     * @param userId
     * @return
     */
    @Query(value = "select count(*) from user_roles where user_id = ?1",nativeQuery = true)
    int queryCountUserRoles(Long userId);

    /**
     * 根据用户ID删除关联表数据
     * @param userId
     * @return
     */
    @Modifying
    @Query(value = "delete from user_roles where user_id = ?1",nativeQuery = true)
    int deleteUserRolesByUserId(Long userId);

    /**
     * 根据ID删除用户及其关联信息
     * @param id
     * @return
     */
    @Modifying
    @Query(value = "delete from user where id = ?1",nativeQuery = true)
    int deleteUserById(Long id);

    /**
     * 修改密码
     * @param password
     * @param id
     * @return
     */
    @Modifying
    @Query(value = "update user set password = ?1 where id = ?2",nativeQuery = true)
    int updatePassword(String password,Long id);

    @Modifying
    @Query(value = "insert into login_record where id = ?1",nativeQuery = true)
    void recordLoginCount(String userName, String name);
}
